from flask import Blueprint, jsonify, request
from app.models.Skillc2 import Food
from app import db

food_bp = Blueprint('food', __name__)

@food_bp.route('/foods', methods=['GET'])
def get_foods():
    """获取食品列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        food_type = request.args.get('type')

        query = Food.query
        if food_type:
            query = query.filter_by(FoodType=food_type)

        foods = query.paginate(page=page, per_page=per_page)

        return jsonify({
            'status': 'success',
            'data': [{
                'id': food.FoodId,
                'name': food.FoodName,
                'price': food.FoodPrice,
                'detail': food.FoodDetail,
                'image': food.FoodImage,
                'type': food.FoodType
            } for food in foods.items],
            'total': foods.total,
            'pages': foods.pages,
            'current_page': page
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@food_bp.route('/foods/<int:food_id>', methods=['GET'])
def get_food(food_id):
    """获取单个食品信息"""
    try:
        food = Food.query.filter_by(FoodId=food_id).first()
        
        if not food:
            return jsonify({
                'status': 'error',
                'message': f'未找到ID为 {food_id} 的食品'
            }), 404
            
        return jsonify({
            'status': 'success',
            'data': {
                'id': food.FoodId,
                'name': food.FoodName,
                'price': food.FoodPrice,
                'detail': food.FoodDetail,
                'image': food.FoodImage,
                'type': food.FoodType
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@food_bp.route('/foods', methods=['POST'])
def create_food():
    """创建新食品"""
    try:
        data = request.get_json()

        if not data or not all(key in data for key in ['name', 'price', 'detail', 'image', 'type']):
            return jsonify({
                'status': 'error',
                'message': '缺少必要的字段'
            }), 400

        food = Food(
            FoodName=data['name'],
            FoodPrice=data['price'],
            FoodDetail=data['detail'],
            FoodImage=data['image'],
            FoodType=data['type']
        )

        db.session.add(food)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '食品创建成功',
            'data': {
                'id': food.FoodId,
                'name': food.FoodName,
                'price': food.FoodPrice,
                'detail': food.FoodDetail,
                'image': food.FoodImage,
                'type': food.FoodType
            }
        }), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@food_bp.route('/foods/types', methods=['GET'])
def get_food_types():
    """获取所有食品类型"""
    try:
        types = db.session.query(Food.FoodType).distinct().all()
        food_types = [t[0] for t in types]
        
        return jsonify({
            'status': 'success',
            'data': food_types
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500